﻿using Newtonsoft.Json;

namespace StarsAdmin.Core.Extensions.Json.Converters
{
    /// <summary>
    /// JSON extentions
    /// </summary>
    public class JsonStringTrimConverter : JsonConverter
    {
        /// <summary>
        /// 确定此实例是否可以转换指定的对象类型。
        /// </summary>
        /// <param name="objectType"></param>
        /// <returns></returns>
        public override bool CanConvert(Type objectType)
        {
            return objectType == typeof(string);
        }

        /// <summary>
        /// 读取对象的JSON表示形式。
        /// </summary>
        /// <param name="reader"></param>
        /// <param name="objectType"></param>
        /// <param name="existingValue"></param>
        /// <param name="serializer"></param>
        /// <returns></returns>
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (objectType == typeof(string) && reader.Value != null)
            {
                if (reader.TokenType == JsonToken.Date)
                {
                    return Convert.ToDateTime(reader.Value).ToString("yyyy-MM-dd HH:mm:ss");
                } else
                {
                    return (reader.Value as string).Trim();
                }
            }
            return reader.Value;
        }

        /// <summary>
        /// 写入对象的JSON表示形式。
        /// </summary>
        /// <param name="writer"></param>
        /// <param name="value"></param>
        /// <param name="serializer"></param>
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            var text = (string)value;
            if (text == null)
            {
                writer.WriteNull();
            } else
            {
                writer.WriteValue(text.Trim());
            }
        }
    }
}